<template>
	<view class="loading-container">
		<view v-if="props.loadingState != completeStateRef" class="loading-box" :style="{ background: props.bgColor }">
			<view v-if="props.loadingState == loadingStateRef">
				<u-loading-icon :vertical="true" size="60rpx" mode="circle" color="#19AEA5" text="加载中..."
					textColor="#19AEA5" textSize="26rpx">
					></u-loading-icon>
			</view>
			<view v-if="props.loadingState != loadingStateRef && emptyResultRef.img" class="loading-empty-box">
				<image :src="emptyResultRef.img" mode="aspectFill" />
				<view @click="onRetry">
					{{ emptyResultRef.title }},
					<text class="loading-empty-box-retry">请稍后重试</text>
				</view>
			</view>
		</view>
		<slot></slot>
	</view>
</template>


<script setup lang="ts">
	import {
		computed,
		ref
	} from "vue";
	import {
		CYLoadingState,
		EmptyImgUrls
	} from "./loading-state";
	import type {
		IEmptyDesc
	} from "./types";

	const props = withDefaults(defineProps < {
		loadingState ? : CYLoadingState,
		bgColor ? : string,
	} > (), {
		loadingState: CYLoadingState.loading,
		bgColor: '#fff',
	})

	const emits = defineEmits(['onRetry']);

	const completeStateRef = ref(CYLoadingState.complete);
	const loadingStateRef = ref(CYLoadingState.loading);

	const emptyResultRef = computed < IEmptyDesc > (() => {
		let loadingState = props.loadingState;
		if (loadingState == CYLoadingState.empty) {
			return {
				title: "暂无数据",
				img: EmptyImgUrls.data,
			};
		} else if (loadingState == CYLoadingState.noNetwork) {
			return {
				title: "网络异常",
				img: EmptyImgUrls.wifi,
			};
		} else if (loadingState == CYLoadingState.error) {
			return {
				title: "出错了",
				img: EmptyImgUrls.page,
			};
		}

		return {
			title: "暂无数据",
			img: EmptyImgUrls.data,
		};
	});

	function onRetry() {
		emits('onRetry');
	}
</script>


<style lang="scss" scoped>
	.loading-container {
		font-size: 28rpx;
		color: #777;

		.loading-box {
			position: absolute;
			left: 0;
			right: 0;
			top: 0;
			bottom: 0;
			z-index: 99;
			background: #fff;
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;

			.loading-box-status {
				margin-top: 30rpx;
			}

			.loading-empty-box {
				display: flex;
				flex-direction: column;
				align-items: center;

				.loading-empty-box-retry {
					color: #064785;
					text-decoration: underline;
				}
			}
		}
	}
</style>
